package com.csun.cmny.provider.consumer.message.jpush;

import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.csun.cmny.base.constant.MessageConstant;
import com.csun.cmny.provider.consumer.message.MessageSender;
import com.csun.cmny.provider.model.dto.SendMessageRequest;
import com.csun.cmny.util.PublicUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-11-07 15:43
 * @Description:
 */
@Slf4j
@Component
public class JPushMessageBuilder {

    public PushPayload build(SendMessageRequest sendMessageRequest) {

        String notification_title = sendMessageRequest.getMessageTitle();
        String msg_title = sendMessageRequest.getMessageTitle();
        String msg_content = sendMessageRequest.getMessage();
        String sound = sendMessageRequest.getSound();

        Map map = JSONObject.fromObject(sendMessageRequest.getExtrasParam());
        map.put("msgType", sendMessageRequest.getMsgCode());    // 注意
        String extras_param = map.toString();

        switch (sendMessageRequest.getShow()) {
            case MessageConstant.MESSAGE_SHOW_NO :
                return buildCustomPushPayload(notification_title, msg_title, msg_content, extras_param, sendMessageRequest.getTagList());
            case MessageConstant.MESSAGE_SHOW_YES :
                if (PublicUtil.isEmpty(sound)) {
                    sound = "sound.caf";
                }
                return buildPushObject_android_and_ios(notification_title, msg_title, msg_content, extras_param, sendMessageRequest.getTagList(), sound);
        }

        return null;
    }

    /**
     * 构建Android和IOS的自定义消息的推送通知对象
     *
     * @return PushPayload
     */
    PushPayload buildCustomPushPayload(String notification_title, String msg_title, String msg_content, String extras_param,
                                                      List<String> tagList) {
        // 批量删除数组中空元素
//        String[] newAlias = removeArrayEmptyElement(alias);
        return PushPayload.newBuilder().setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(tagList))
                .setMessage(Message.newBuilder()
                        .setTitle(msg_title)
                        .setMsgContent(msg_content)
                        .addExtra("message extras key", extras_param).build())
                .build();
    }

    PushPayload buildPushObject_android_and_ios(String notification_title, String msg_title, String msg_content, String extras_param, List<String> tagList, String sound) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(tagList))
                .setNotification(Notification.newBuilder()
                        .setAlert(notification_title)
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(notification_title)
                                //.setTitle(notification_title)
                                //此字段为透传字段，不会显示在通知栏。用户可以通过此字段来做一些定制需求，如特定的key传要指定跳转的页面（value）
                                .addExtra("androidNotification extras key", extras_param)
                                .build()
                        )
                        .addPlatformNotification(IosNotification.newBuilder()
                                //传一个IosAlert对象，指定apns title、title、subtitle等
                                .setAlert(notification_title)
                                //直接传alert
                                //此项是指定此推送的badge自动加1
                                .incrBadge(1)
                                //此字段的值default表示系统默认声音；传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒，
                                // 如果系统没有此音频则以系统默认声音提醒；此字段如果传空字符串，iOS9及以上的系统是无声音提醒，以下的系统是默认声音
                                .setSound(sound)
                                //此字段为透传字段，不会显示在通知栏。用户可以通过此字段来做一些定制需求，如特定的key传要指定跳转的页面（value）
                                .addExtra("iosNotification extras key", extras_param)
                                //此项说明此推送是一个background推送，想了解background看：http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
                                // .setContentAvailable(true)

                                .build()
                        )
                        .build()
                )
                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息，
                // sdk默认不做任何处理，不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
                // [通知与自定义消息有什么区别？]了解通知和自定义消息的区别
//                .setMessage(Message.newBuilder()
//                        .setMsgContent(msg_content)
//                        .setTitle(msg_title)
//                        .addExtra("message extras key", extras_param)
//                        .build())

                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境，false表示开发，true表示生产；对android和自定义消息无意义
                        .setApnsProduction(false)
                        //此字段是给开发者自己给推送编号，方便推送者分辨推送记录
                        .setSendno(1)
                        //此字段的值是用来指定本推送的离线保存时长，如果不传此字段则默认保存一天，最多指定保留十天，单位为秒
                        .setTimeToLive(86400)
                        .build()
                )
                .build();
    }

    /**
     * 删除别名中的空元素（需删除如：null,""," "）
     *
     * @param strArray
     * @return String[]
     */
    String[] removeArrayEmptyElement(String... strArray) {
        if (null == strArray || strArray.length == 0) {
            return null;
        }
        List<String> tempList = Arrays.asList(strArray);
        List<String> strList = new ArrayList<String>();
        Iterator<String> iterator = tempList.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            // 消除空格后再做比较
            if (null != str && !"".equals(str.trim())) {
                strList.add(str);
            }
        }
        // 若仅输入"",则会将数组长度置为0
        String[] newStrArray = strList.toArray(new String[strList.size()]);
        return newStrArray;
    }
}
